//初步思路：创建画布-》 绘制元素 -》 动态更新元素  -》事件监听、绑定 -》 分数等级


function init(){
	speed = 900;			//速度
	sum = 0;				//分数
	black = [];
	status = 0; //初始状态
	missNum = 0;
	pauseStatus = 0;
	s = 0;
	b = 0;
	
	bodyW = document.body.clientWidth;
	canvasW = bodyW>960?960:bodyW;
	canvasW = canvasW<240?240:canvasW;
	bg.width = canvasW;
//	startContainer.width = canvasW;
	score.innerHTML=sum;
	
	blockWidth = Math.floor(bg.offsetWidth/4);
	blockHeight = Math.floor(bg.offsetHeight/8);
	scro.style.height=blockHeight+'px';
	scro.style.lineHeight=blockHeight+'px';
	startContainer.style.width = canvasW +'px';
}

//抓取元素
function getElement(){
	bg = document.getElementById('bg');
	score = document.getElementById('score');
	scro = document.getElementById('scro');
	 miss = document.getElementById('life');
	pause = document.getElementById('pause');
	start = document.getElementById('start');
	userName = document.getElementById('userName');
	userNameText = document.getElementById('userNameText');	
	startContainer = document.getElementById('startContainer');	
	play = document.getElementById('play');
}

//获取用户信息
function getUser(){
//	localStorage['user_name'] = '';
	historyUserName = localStorage.getItem('user_name');
	historyHightScore = localStorage.getItem('score');
	
	if(typeof(historyUserName) == 'string' && historyUserName != ''){
		userNameText.innerHTML = "<ul><li><sapn>用户名："+historyUserName+"</sapn></li><li><sapn>历史最高得分："+historyHightScore+"</sapn></li></ul>"
	}
}
//用户名验证
function illegalChar(str)
{
    var pattern=/[`~!@#\$%\^\&\*\(\)_\+<>\?:"\{\},\.\\\/;'\[\]]/im;  
    if(pattern.test(str)){  
        return false;     
    }     
    return true;  
}

function loading(){
	getElement();
	init();
	getUser();
}

function gameOver(){
	clearInterval(timer);
	if(historyHightScore){
		if(historyHightScore<sum){
			localStorage['score'] = sum;
		}
	}else{
		localStorage['score'] = sum;
	}
	missNum = 0;
	sum = 0;
	miss.innerHTML = missNum;
	score.innerHTML=sum;
	alert('GAME OVER');
	//重新开始
	location.reload();
	//结束游戏 返回首页
}
//创建初始化色块
function block(){
	this.row = [];

	//生成坐标
	for(var i=0;i<8;i++){
			this.row[i] = [];
		for(var c=0;c<4;c++){
			this.row[i][c]= [];
			this.row[i][c]=[c*blockWidth,i*blockHeight,'white','0'];
//			this.row[i][c][0]=(c+1)*blockWidth-blockWidth;//x坐标
//			this.row[i][c][1]=i*blockHeight;//y坐标
//			this.row[i][c][2]='white';		//颜色
		}
	}

	//定义初始化颜色
	this.color=function(){
		for(var co=0;co<this.row.length;co++){
			num = Math.floor(Math.random()*(4-0)+0);
			black.push(num);
			for(var cl=0;cl<this.row[co].length;cl++){
				blockColor = cl==num?'black':'white';
				this.row[co][cl][2] = blockColor;
			}
		}		
	}
	
	//定义默认边界高度
	boxHeight = this.row.length * blockHeight +5 ;
	
	//绘制边框线
	this.drawBorder = function(){
		this._row = bg.getContext('2d');
		this._row.lineWidth=1;
		this._row.strokeStyle="black";
		//画黑白块
		for(var r=0;r<this.row.length;r++){	
			for(var c=0;c<this.row[r].length;c++ ){
				this._row.beginPath();
				this._row.strokeRect(this.row[r][c][0],this.row[r][c][1]+r*2,blockBorderWidth,blockBorderHeight);
				this._row.closePath();
			}
		}
	}
	//正确绘制
	this.drawRight = function(W,H){
			this._row = bg.getContext('2d');
			this._row.beginPath();
			this._row.fillStyle='blue';
			this._row.fillRect(W,H,blockWidth,blockHeight);
			this._row.lineWidth = 5;
			this._row.strokeStyle="#fff";
			this._row.moveTo(W + blockWidth/5,H + blockHeight/5);
			this._row.lineTo(W+blockWidth/3,H+blockHeight - blockHeight/5);
			this._row.lineTo(W+blockWidth - blockWidth/7,H +  blockHeight/8);
			this._row.stroke();
			this._row.closePath();
	}
	//错误绘制
	this.drawWrong = function(W,H){
			this._row = bg.getContext('2d');
			this._row.beginPath();
			this._row.fillStyle='red';
			this._row.fillRect(W,H,blockWidth,blockHeight);
			this._row.closePath();
			this._row.lineWidth = 5;
			this._row.strokeStyle="yellow";
			this._row.moveTo(W,H);
			this._row.lineTo(W+blockWidth,H+blockHeight);
			this._row.stroke();
			this._row.moveTo(W,H+blockHeight);
			this._row.lineTo(W+blockWidth,H);
			this._row.stroke();
			this._row.closePath();
	}
	
	//点击事件
	this.click= function(x,y){
		H  = Math.floor( y / blockHeight ) ;  //行数 		
		W  = Math.floor( x / blockWidth ) ;	//列数
		//点击位置对错判断
		
		if(black[H] == W){
//			Hnum = s>6?H:H+1;	
			b ++;
			
			Hnum = b>=9?H:H+1;

			//判断父级是否已经消除
			if(black[H + 1] == -1 || black.length == H + 1){
				black[H] = -1;
				sum += 1;
				score.innerHTML=sum;
				//对-》反馈效果
				this.drawRight(W*blockWidth,H*blockHeight);
				this.row[Hnum][W][3] = '1';
				console.log('this.row状态:==>'+Hnum+W);
			}else{
				this.drawWrong(W*blockWidth,H*blockHeight);
//				this.row[H][W][2] = 'red';
				this.row[Hnum][W][3] = '2';
				missNum ++;
				miss.innerHTML = missNum;
				if(missNum>= 10){
					gameOver();
				}
			}
		}else if(black[H] == -1){
			
		}else{
			//错误->反馈效果
			this.drawWrong(W*blockWidth,H*blockHeight);
//			this.row[H][W][2] = 'red';
			this.row[Hnum][W][3] = '2';
			missNum ++;
			miss.innerHTML = missNum;
			if(missNum>= 10){
				gameOver();
			}
		}
	}
	this.draw =function(){
			
			this._row = bg.getContext('2d');
			this._row.strokeStyle='black';
			this._row.lineWidth='1';
			//画黑白块
			for(var r=0;r<this.row.length;r++){	
				for(var c=0;c<this.row[r].length;c++ ){
					this._row.beginPath();
					this._row.fillStyle=this.row[r][c][2];
					this._row.fillRect(this.row[r][c][0],this.row[r][c][1],blockWidth,blockHeight);					
//					this._row.closePath();
					if(Number(this.row[r][c][3]) != 0){
//						alert(this.row[r][c][3])
						if(this.row[r][c][3] == '1'){
							this.drawRight(this.row[r][c][0],this.row[r][c][1]);
						}else if(this.row[r][c][3] == '2'){						
							this.drawWrong(this.row[r][c][0],this.row[r][c][1]);
						}
					}
				}
			}
			//移除最后一行
//			this.row.pop();
			
			//添加新坐标
			var newArray = [];
			for(var c=0;c<4;c++){
				newArray[c] = [c*blockWidth,0,'white'] ;
			}
			//给新添加的定义颜色			
			num = Math.floor(Math.random()*(4-0)+0);
			newArray[num][2] = 'black'; 
			//头部追加行			
			this.row.unshift(newArray);	
			
			//更新坐标
			for(var co=0;co<this.row.length;co++){
				for(var cl=0;cl<this.row[co].length;cl++){
					this.row[co][cl][1] = this.row[co][cl][1] +blockHeight;
				}
			}

		
			//超出边界  移除数组  miss+1
			if(this.row[this.row.length-1][0][1] >= bg.offsetHeight+5){
				s++;
				if(black[black.length-1] != -1){  //类型判断
					missNum +=1;
					miss.innerHTML = missNum;
					if(missNum >= 10){
						gameOver();
					}
				}
				
				this.row.pop();				
				black.pop();
				black.unshift(num);
			}


	}

}
//游戏开始
function gameStart(){
	start.style.display = 'none';
	scro.style.display = 'block';
	block = new block;
	block.color();
	block.draw();
	bg.onclick=function(e){
		e=e||event;//获取时间对象
		var x=e.clientX-bg.offsetLeft;
		var y=e.clientY-bg.offsetTop;
		block.click(x,y);
	}
	
	timer = setInterval('block.draw()',speed);
}
//加载完成执行
window.onload =function(){
	loading();


	//点击开始操作
play.onclick = function(){
	if(typeof(historyUserName) == 'string' && historyUserName != ''){		
		gameStart();	
	}else{
		user = userName.value;
		if(user.length>0){
			if(illegalChar(user)){
				localStorage['user_name'] =user;

				gameStart();
			}else{
				alert('用户名不能包含特殊字符');
			}
		}
	}
}

   //暂停 /开始  
   pause.onclick= function(){
   	if(pauseStatus == 0){
   	 	clearInterval(timer);
   	 	pause.innerHTML ='开始';
   	 	pauseStatus = 1;   	 	
   	}else{
   		timer = setInterval('block.draw()',speed);
   		pauseStatus = 0;  
   		pause.innerHTML ='暂停';
   	}
   }

}
